package com.yhh.weixin.service.impl;

import com.yhh.common.base.ret.ApiResult;
import com.yhh.weixin.service.WeixinService;
import com.yhh.weixin.util.WeixinConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Service
public class WeixinServiceImpl implements WeixinService {
    @Autowired
    private WeixinConfig weixinConfig;
    @Autowired
    private RestTemplate restTemplate;
    @Override
    public ApiResult getWXQRCode(String state) {
        // 对回调地址进行URLEncode
        String url = null;
        try {
            url = URLEncoder.encode(weixinConfig.getRedirectUrl(),"GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return ApiResult.error("对回调地址进行URLEncode编码失败");
        }
        //对用户扫的二维码设置参数
        String qrCode = String.format(weixinConfig.getUserAuthUrl(), weixinConfig.getAppid(), url, state);
        return ApiResult.success().put("qrCode",qrCode);
    }
    @Override
    public ApiResult getAccessToken(String code) {
        // 给网页授权access_token 请求地址设置参数
        String url = String.format(weixinConfig.getAccessTokenUrl(), weixinConfig.getAppid(), weixinConfig.getAppsecret(), code);
        // 发起远程get请求，并接收返回结果
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
        if(forEntity == null || forEntity.getStatusCodeValue() != 200){
            return ApiResult.error("调用网页授权地址失败");
        }
        return ApiResult.success().put("body",forEntity.getBody());
    }
    @Override
    public ApiResult getWXUserinfo(String accessToken, String openId) {
        // 给拉取微信用户信息的请求地址设置参数
        String url = String.format(weixinConfig.getUserInfoUrl(), accessToken, openId);
        // 发起远程get请求，并接收返回结果
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
        if(forEntity == null || forEntity.getStatusCodeValue() != 200){
            return ApiResult.error("调用微信用户信息的请求地址失败");
        }
        return ApiResult.success().put("body",forEntity.getBody());
    }
}
